import { createStore } from 'vuex'
import storage from '../utils/storage/index'
import {setToken,getToken,removeToken} from '../utils/auth' 
import { login, logOut } from '../localhttp/loginApi' 
import sysConstant from '../utils/constant'

const userLocal=storage.localGet(sysConstant.currentUser);
const currentUser = userLocal&&JSON.parse(userLocal)||{};

export default createStore({
  state: {
    currentUser:currentUser, 
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    permissions: []
  },
  mutations: {
    setCurrentUser (state, value) {
      state.currentUser = value; 
    },
    setToken (state, value) {
      state.token = value
    },
    setName (state, value) {
      state.name = value
    },
  },
  actions: {
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login({ "name": userInfo.username.trim(), "password": userInfo.password }).then((res: any) => {
          //console.log('res=====.data.token====>', res.data.token); 
          if (res.code == 200) {
            commit("setCurrentUser", res.data);
            commit("setToken", res.data.token);
            commit("setName", res.data.name);
            storage.localSet(sysConstant.currentUser, JSON.stringify(res.data))
            setToken(res?.data?.token);
          }
          resolve(res.data);
        }).catch(error => {
          reject(error)
        });
      })
    },
    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logOut(state.token).then((res) => {
          commit('setToken', '');
          commit("setCurrentUser", {});
          storage.localRemove(sysConstant.currentUser);
          removeToken();
          resolve(res.data);
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('setToken', '');
        commit("setCurrentUser", {});
        storage.localRemove(sysConstant.currentUser);
        removeToken();
        resolve("ok");
      })
    }
  },
  modules: {
    
  }
})
